package cn.tangsihai.basic.controller;

import cn.tangsihai.basic.util.AjaxResult;
import cn.tangsihai.basic.util.FastDfsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/common/fastDfs")
@Api(tags = "店铺入驻接口",description = "店铺入驻接口详细描述")
public class FastDfsController {
    @PostMapping
    // @RequestPart(required = true,value = "file")：接收混合类型请求参数时
    @ApiOperation(value = "上传")
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){
        try {
            // 获取上传文件的后缀  substring截取字符串，含头不含尾
            String filename = file.getOriginalFilename(); // 文件名：xxx.yyy.后缀
            String extName = filename.substring(filename.lastIndexOf(".") + 1); // 后缀
            // 调用工具类中的上传文件方法
            String address = FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(address);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("上传失败");
        }
    }


    @DeleteMapping
    // @RequestParam：用于接收“请求地址/?xxx=yyy类型的请求参数”
    @ApiOperation(value = "删除")
    public AjaxResult del(@RequestParam String path){ // path：/group1/xxx/xxx/xxxx.后缀
        try {
            // 获取groupName
            String path1 = path.substring(1);
            String groupName = path1.substring(0, path1.indexOf("/"));
            // 获取fileName 注：这里的fileName是组名后第一个/后面的都是文件名
            String fileName = path1.substring(path1.indexOf("/") + 1);
            // 调用删除方法
            FastDfsUtil.delete(groupName, fileName);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("删除失败");
        }
    }

}
